import 'package:base/main.dart';
import 'package:flutter/material.dart';
import 'package:framework/main.dart';
import 'package:module_discover/enums/domain_type_enum.dart';
import 'package:module_discover/pages/filter_domain/filter_domain_logic.dart';
import 'package:module_discover/pages/filter_domain/view/round_input_field.dart';
import 'package:module_discover/pages/filter_domain/widgets/child/child_checkbox_widget.dart';
import 'package:module_discover/pages/model/Domain_info_model.dart';
import 'package:module_discover/pages/model/filter_model.dart';

/// 输入框 类型
class ChildInputWidget extends StatefulWidget {
  /// 传参
  final BaseFilterItem child;
  final String parentKey;

  const ChildInputWidget({
    super.key,
    required this.child,
    required this.parentKey,
  });

  @override
  State<ChildInputWidget> createState() => _ChildInputWidgetState();
}

class _ChildInputWidgetState extends State<ChildInputWidget> {
  final FilterDomainLogic logic = Get.find<FilterDomainLogic>();
  late String name;
  late DomainTypeEnum domainType;
  late String childKey;
  Map<String, bool> isGjzMap = {};
  Map<String, String> nameKeyMap = {};

  @override
  void initState() {
    super.initState();
  }

  initData() {
    name = widget.child.title ?? "";
    domainType =
        DomainTypeEnum.fromValue(widget.child.type) ?? DomainTypeEnum.OTHER;
    childKey = widget.child.key ?? "";

    DomainInfoModel? model =
        logic.filterPreviewVM.selectedMaps[widget.parentKey]?[childKey];

    if (model == null) {
      logic.selectInputVM.getController(widget.child.key).text = "";
      isGjzMap.forEach((key, value) {
        isGjzMap[key] = false;
      });
      for (var option in widget.child.children) {
        nameKeyMap[option.key] = option.title;
      }
      return;
    }
    final parts = model.value.split("|");
    final dataMap = Map.fromEntries(parts.map((part) {
      if (part.contains('=')) {
        final kv = part.split('=');
        return MapEntry(kv[0], kv.length > 1 ? kv[1] : null);
      }
      return MapEntry(part, null); // 无等号的值设为 null
    }));

    dataMap.forEach((key, value) {
      if (key != childKey) {
        if (value == "1") {
          isGjzMap[key] = true;
        }
      }
    });
    final value = dataMap[childKey];
    if (value != null) {
      logic.selectInputVM.getController(widget.child.key).text = value;
    }
    for (var option in widget.child.children) {
      nameKeyMap[option.key] = option.title;
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  _checkInput() {
    final hasText = logic.selectInputVM
        .getController(widget.child.key)
        .text
        .trim()
        .isNotEmpty;
    String keyName =
        logic.selectInputVM.getController(widget.child.key).text.trim();
    String value = "$childKey=$keyName";
    if (hasText) {
      isGjzMap.forEach((key, check) {
        if (check) {
          keyName += "、${nameKeyMap[key]}";
          value += "|$key=1";
        }
      });
    } else {
      value = "";
    }
    logic.filterPreviewVM.setSelectedMaps(
        domainType, name, widget.parentKey, childKey, keyName, value);
  }

  @override
  Widget build(BuildContext context) {
    initData();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        RoundInputField(
          hintText: "多个,分隔",
          logic: logic,
          fieldKey: widget.child.key,
          onChanged: (value) {
            _checkInput();
          },
        ),
        _buildItemWidget(widget.child.children),
      ],
    );
  }

  _buildItemWidget(List<BaseFilterItem>? optional) {
    if (optional == null || optional.isEmpty) {
      return SizedBox();
    }
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Wrap(
        spacing: Constants.px_6,
        runSpacing: Constants.px_10,
        children: List.generate(optional.length, (index) {
          BaseFilterItem option = optional[index];
          final key = option.key;
          final type = DomainTypeEnum.fromValue(option.type!);
          bool? check = isGjzMap[key] ?? false;
          if (type == DomainTypeEnum.CHECKBOX) {
            return ChildBxoWidget(
              option: option,
              isCheck: check,
              onChanged: (bool? value) {
                isGjzMap[key] = value!;
                _checkInput();
              },
            );
          } else {
            return SizedBox();
          }
        }),
      ),
    );
  }
}
